import { useState, useEffect, useContext } from "react";
import { AuthContext } from "@/App";
import { useNavigate } from "react-router-dom";
import { cn } from "@/lib/utils";
import { useTheme } from "@/hooks/useTheme";
import { motion } from "framer-motion";
import { toast } from "sonner";
import UserService from "@/services/user";

export default function UserList() {
  const { isAuthenticated, userInfo, logout } = useContext(AuthContext);
  const navigate = useNavigate();
  const { theme, toggleTheme, isDark } = useTheme();
  const [users, setUsers] = useState<any[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newUser, setNewUser] = useState({
    userName: "",
    userIcon: "fa-solid fa-user",
    account: "",
    password: ""
  });
  const [editingUser, setEditingUser] = useState<any | null>(null);

  useEffect(() => {
    // 模拟加载用户数据
    const mockUsers = [
      {
        userId: "1",
        userName: "管理员",
        userIcon: "fa-solid fa-user-shield",
        account: "admin",
        createUser: "1",
        createTime: "2025-06-01T10:00:00Z"
      }
    ];
    setUsers(mockUsers);
  }, []);

  const handleCreateUser = () => {
    if (!newUser.userName.trim() || !newUser.account.trim() || !newUser.password) {
      toast.error("请填写完整用户信息");
      return;
    }

    const user = {
      userId: Date.now().toString(),
      ...newUser,
      createUser: "1", // 当前登录用户ID
      createTime: new Date().toISOString()
    };

    setUsers([...users, user]);
    setShowCreateModal(false);
    setNewUser({
      userName: "",
      userIcon: "fa-solid fa-user",
      account: "",
      password: ""
    });
    toast.success(`用户 ${user.userName} 创建成功`);
  };

  const handleUpdateUser = () => {
    if (!editingUser || !editingUser.userName.trim() || !editingUser.account.trim()) {
      toast.error("请填写完整用户信息");
      return;
    }

    setUsers(users.map(u => 
      u.userId === editingUser.userId ? editingUser : u
    ));
    setEditingUser(null);
    toast.success("用户信息已更新");
  };

  const handleDeleteUser = (userId: string) => {
    const userName = users.find(u => u.userId === userId)?.userName;
    setUsers(users.filter(user => user.userId !== userId));
    toast.success(`用户 ${userName} 已删除`);
  };

  const iconOptions = [
    "fa-solid fa-user",
    "fa-solid fa-user-shield",
    "fa-solid fa-user-tie",
    "fa-solid fa-user-ninja",
    "fa-solid fa-user-astronaut",
    "fa-solid fa-user-graduate",
    "fa-solid fa-user-md"
  ];

  return (
    <div className={cn(
      "min-h-screen flex flex-col bg-transparent",
      isDark ? "text-gray-100" : "text-gray-900"
    )}>
      {/* 导航栏 */}
      <header className={cn(
        "sticky top-0 z-10 p-2 border-b",
        isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <button 
              onClick={() => navigate(-1)}
              className={cn(
                "px-3 py-1 rounded-md font-mono flex items-center",
                isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
              )}
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回
            </button>
            <h1 className="font-mono font-bold text-xl">用户管理</h1>
          </div>
          
          <div className="flex items-center space-x-4">
            <button 
              onClick={() => setShowCreateModal(true)}
              className={cn(
                "px-4 py-2 rounded-md font-medium",
                isDark 
                  ? "bg-blue-600 hover:bg-blue-700" 
                  : "bg-orange-500 hover:bg-orange-600",
                "text-white"
              )}
            >
              <i className="fa-solid fa-plus mr-2"></i>
              新建用户
            </button>
            <button 
              onClick={toggleTheme}
              className={cn(
                "w-10 h-10 rounded-full flex items-center justify-center",
                isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
              )}
            >
              <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
            </button>
          </div>
        </div>
        <button 
          onClick={toggleTheme}
          className={cn(
            "w-10 h-10 rounded-full flex items-center justify-center",
            isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
          )}
        >
          <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
        </button>
        {isAuthenticated && (
          <div className="relative group">
            <button className="flex items-center">
              <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                {userInfo?.userIcon ? (
                  <i className={cn(
                    userInfo.userIcon,
                    "text-xl",
                    isDark ? "text-blue-400" : "text-orange-500"
                  )}></i>
                ) : (
                  <i className="fa-solid fa-user text-gray-600 dark:text-gray-300"></i>
                )}
              </div>
            </button>
            <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all">
              <div className="py-1">
                <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200">
                  {userInfo?.userName || '用户'}
                </div>
                <button 
                  onClick={logout}
                  className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                >
                  <i className="fa-solid fa-right-from-bracket mr-2"></i>
                  退登
                </button>
              </div>
            </div>
          </div>
        )}
      </header>

      {/* 用户列表 */}
      <main className="flex-1 container mx-auto p-4 md:p-8">
        {users.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full py-12">
            <i className="fa-solid fa-users text-5xl mb-4 opacity-30"></i>
            <h2 className="text-xl font-mono mb-4">暂无用户数据</h2>
            <button 
              onClick={() => setShowCreateModal(true)}
              className={cn(
                "px-6 py-2 rounded-md font-medium",
                isDark 
                  ? "bg-blue-600 hover:bg-blue-700" 
                  : "bg-orange-500 hover:bg-orange-600",
                "text-white"
              )}
            >
              <i className="fa-solid fa-plus mr-2"></i>
              创建第一个用户
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {users.map(user => (
              <motion.div
                key={user.userId}
                whileHover={{ y: -5 }}
                className={cn(
                  "p-4 rounded-xl shadow-md",
                  isDark ? "bg-gray-800" : "bg-white"
                )}
              >
                <div className="flex items-center space-x-3 mb-3">
                  <i className={cn(
                    user.userIcon,
                    "text-2xl",
                    isDark ? "text-blue-400" : "text-orange-500"
                  )}></i>
                  <div>
                    <h3 className="font-mono font-bold">{user.userName}</h3>
                    <p className="text-sm text-gray-500">{user.account}</p>
                  </div>
                </div>
                <div className="text-sm mb-3">
                  <p className="font-mono">创建时间: {new Date(user.createTime).toLocaleString()}</p>
                </div>
                <div className="flex justify-end space-x-2">
                  <button
                    onClick={() => setEditingUser(user)}
                    className={cn(
                      "px-3 py-1 rounded-md text-sm",
                      isDark ? "bg-blue-600 hover:bg-blue-700" : "bg-blue-500 hover:bg-blue-600",
                      "text-white"
                    )}
                  >
                    <i className="fa-solid fa-pen mr-1"></i>
                    编辑
                  </button>
                  <button
                    onClick={() => handleDeleteUser(user.userId)}
                    className={cn(
                      "px-3 py-1 rounded-md text-sm",
                      isDark ? "bg-red-600 hover:bg-red-700" : "bg-red-500 hover:bg-red-600",
                      "text-white"
                    )}
                  >
                    <i className="fa-solid fa-trash mr-1"></i>
                    删除
                  </button>
                </div>
              </motion.div>
            ))}
          </div>
        )}
      </main>

      {/* 新建用户模态框 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "w-full max-w-md p-6 rounded-xl shadow-lg",
              isDark ? "bg-gray-800" : "bg-white"
            )}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="font-mono font-bold text-xl">新建用户</h2>
              <button
                onClick={() => setShowCreateModal(false)}
                className={cn(
                  "p-1 rounded-full",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block font-mono text-sm mb-1">用户名</label>
                <input
                  type="text"
                  value={newUser.userName}
                  onChange={(e) => setNewUser({...newUser, userName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入用户名"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">账号</label>
                <input
                  type="text"
                  value={newUser.account}
                  onChange={(e) => setNewUser({...newUser, account: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入账号"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">密码</label>
                <input
                  type="password"
                  value={newUser.password}
                  onChange={(e) => setNewUser({...newUser, password: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入密码"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">用户头像</label>
                <div className="grid grid-cols-4 gap-2 mb-2">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setNewUser({...newUser, userIcon: icon})}
                      className={cn(
                        "p-2 rounded-md flex items-center justify-center",
                        newUser.userIcon === icon 
                          ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        newUser.userIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div className="flex justify-end space-x-2">
                <button
                  onClick={() => setShowCreateModal(false)}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                  onClick={handleCreateUser}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-orange-500 hover:bg-orange-600",
                    "text-white"
                  )}
                >
                  创建
                </button>
              </div>
            </div>
          </motion.div>
        </div>
      )}

      {/* 编辑用户模态框 */}
      {editingUser && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "w-full max-w-md p-6 rounded-xl shadow-lg",
              isDark ? "bg-gray-800" : "bg-white"
            )}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="font-mono font-bold text-xl">编辑用户</h2>
              <button
                onClick={() => setEditingUser(null)}
                className={cn(
                  "p-1 rounded-full",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block font-mono text-sm mb-1">用户名</label>
                <input
                  type="text"
                  value={editingUser.userName}
                  onChange={(e) => setEditingUser({...editingUser, userName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入用户名"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">账号</label>
                <input
                  type="text"
                  value={editingUser.account}
                  onChange={(e) => setEditingUser({...editingUser, account: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入账号"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">用户头像</label>
                <div className="grid grid-cols-4 gap-2 mb-2">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setEditingUser({...editingUser, userIcon: icon})}
                      className={cn(
                        "p-2 rounded-md flex items-center justify-center",
                        editingUser.userIcon === icon 
                          ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        editingUser.userIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div className="flex justify-end space-x-2">
                <button
                  onClick={() => setEditingUser(null)}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                  onClick={handleUpdateUser}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-orange-500 hover:bg-orange-600",
                    "text-white"
                  )}
                >
                  保存
                </button>
              </div>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}